package edu.buaa.act.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by T7810 on 2017/3/12.
 */
public class Utils
{
    private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    {
        df.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    }

    public static long timeStr2stamp(String timeStr) throws ParseException {
        return df.parse(timeStr).getTime();
    }

    public static String timestamp2Str(long timestampMilliseconds) {
        return df.format(new Date(timestampMilliseconds));
    }

    public static File getFile(String path)
    {
        return new File(path);
    }

    public static File getExistFile(String path) throws FileNotFoundException
    {
        File f = new File(path);
        if(f.exists()){
            if( f.isFile()){
                return f;
            }else{
                throw new FileNotFoundException("expect file, but dir found.");
            }
        }else{
            throw new FileNotFoundException("file not exist: "+f.getAbsolutePath());
        }
    }

    public static File getOrCreateDir(String path) throws IOException
    {
        File f = new File(path);
        if(f.exists()){
            if( (f.isDirectory())){
                return f;
            }else{
                throw new IOException("expect dir, but file found.");
            }
        }else{
            if(!f.mkdirs()) throw new IOException("create dir failed.");
            return f;
        }
    }

    private static Logger devLog = LoggerFactory.getLogger("dev");
    private static Logger testLog = LoggerFactory.getLogger("test");
    public static Logger getDebugLogger()
    {
        return devLog;
    }

    public static double toFix(double num, int dec) {
        long i  = (long) Math.pow(10,dec);
        long tmp = Math.round(num * i);
        return tmp*1d/i;
    }

    public static double percent(double numerator, double denominator){
        return toFix(numerator*100/denominator, 1);
    }

    public static String rmQuote(String s) {
        String t = s.trim();
        if(t.charAt(0)=='\'' || t.charAt(0)=='"')
        {
            int tl = t.length();
            return t.substring(1, tl - 1);
        }else{
            return t;
        }
    }


}

